package com.yexiao.cofe.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class RabbitMQConfig {

    public static final String BUSINESS_EXCHANGE_NAME = "exchange.coffee";
    public static final String BUSINESS_QUEUE_NAME = "queue.coffee";

    public static final String DEAD_LETTER_EXCHANGE_NAME = "deadletter.exchange";
    public static final String DEAD_LETTER_QUEUE_NAME = "deadletter.queue";

    // 声明业务交换机
    @Bean
    DirectExchange businessExchange() {
        return new DirectExchange(BUSINESS_EXCHANGE_NAME);
    }

    // 声明死信交换机
    @Bean
    DirectExchange deadLetterExchange() {
        return new DirectExchange(DEAD_LETTER_EXCHANGE_NAME);
    }

    // 声明业务队列
    @Bean
    Queue businessQueue() {
        Map<String, Object> args = new HashMap<>(2);
        // 设置死信交换机
        args.put("x-dead-letter-exchange", DEAD_LETTER_EXCHANGE_NAME);
        // 设置死信路由键
        args.put("x-dead-letter-routing-key", "order.expire");
        return new Queue(BUSINESS_QUEUE_NAME, true, false, false, args);
    }

    // 声明死信队列
    @Bean
    Queue deadLetterQueue() {
        return new Queue(DEAD_LETTER_QUEUE_NAME, true);
    }

    // 绑定业务队列到业务交换机
    @Bean
    Binding businessBinding() {
        return BindingBuilder.bind(businessQueue()).to(businessExchange()).with("business.routingkey");
    }

    // 绑定死信队列到死信交换机
    @Bean
    Binding deadLetterBinding() {
        return BindingBuilder.bind(deadLetterQueue()).to(deadLetterExchange()).with("order.expire");
    }
}
